package com.github.pig.admin.controller.park;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.exception.excel.ExcelImportException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.admin.mapper.sys.SysDeptMapper;
import com.github.pig.admin.model.entity.SysDept;
import com.github.pig.admin.model.entity.SysRole;
import com.github.pig.admin.model.park.EmployeeInfo;
import com.github.pig.admin.service.park.IEmployeeInfoService;
import com.github.pig.admin.service.sys.SysDeptService;
import com.github.pig.admin.service.sys.SysRoleService;
import com.github.pig.admin.service.sys.SysUserService;
import com.github.pig.admin.util.AjaxJson;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.R;
import com.github.pig.common.vo.CommunityInfoBean;
import com.github.pig.common.vo.UserVO;
import com.github.pig.common.web.BaseController;
import com.google.common.base.Joiner;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author sxf
 * @since 2018-12-17
 */
@RestController
@RequestMapping("/employeeInfo")
public class EmployeeInfoController extends BaseController {
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysDeptService deptService;
    @Autowired
    private IEmployeeInfoService employeeInfoService;

    @Autowired
    private SysDeptMapper deptMapper;

    /**
     * 通过ID查询
     *
     * @param id ID
     * @return EmployeeInfo
     */
    @GetMapping("/{id}")
    public R<EmployeeInfo> get(@PathVariable String id) {

        return new R<>(employeeInfoService.selectById(id));
    }


    /**
     * 分页查询信息
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @RequestMapping("/page")
    public Page page(@RequestParam Map<String, Object> params, EmployeeInfo info) {
        try {
            params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
            EntityWrapper entityWrapper = new EntityWrapper();
            Page<EmployeeInfo> page = new Page<EmployeeInfo>(Integer.parseInt(params.getOrDefault("page", 1).toString())
                    , Integer.parseInt(params.getOrDefault("limit", 10).toString()));
            String username = getUserName();
            UserVO user = userService.findUserByUsername(username);

            entityWrapper.eq("del_flag", CommonConstant.STATUS_NORMAL);
            if (StringUtils.isNotEmpty(info.getName())) {
                entityWrapper.like("name", info.getName());
            }
            if (StringUtils.isNotEmpty(info.getPhone())) {
                entityWrapper.like("phone", info.getPhone());
            }
            //根据部门查询  获取部门以及子部门往下
            if (params.get("deptId") != null && params.get("deptId") != "") {
                List<SysDept> list = deptMapper.getTreeByCurrentUserDeptId(params.get("deptId").toString(), null);
                List<Integer> deptIds = list.stream().map(SysDept::getDeptId).collect(Collectors.toList());
                entityWrapper.in("dept_id", Joiner.on(",").join(deptIds));
            }
            /**
             * 数据过滤
             */
            if (!CommonConstant.MANAGE_NAME.equals(username)) {
                entityWrapper.in("company_id", user.getCommunityList().stream().map(CommunityInfoBean::getCommunityId).collect(Collectors.joining(",")));
            }
            return employeeInfoService.selectPage(page, entityWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("人事档案查询出错：", e);
            return null;
        }
    }

    /**
     * 添加
     *
     * @param employeeInfo 实体
     * @return success/false
     */
    @PostMapping
    public R<Boolean> add(@RequestBody EmployeeInfo employeeInfo) {
        employeeInfo.setDelFlag(CommonConstant.STATUS_NORMAL);
        return new R<>(employeeInfoService.unionInsert(employeeInfo));
    }

    /**
     * 删除
     *
     * @param id   ID
     * @param quit 删除类型 1离职0信息填写错误
     * @return success/false
     */
    @DeleteMapping("/{id}/{quit}")
    public R<Boolean> delete(@PathVariable String id, @PathVariable String quit) {
        EmployeeInfo employeeInfo = new EmployeeInfo();
        employeeInfo.setId(id);
        employeeInfo.setQuit(quit);
        employeeInfo.setQuitTime(new Date());
        employeeInfo.setUpdateTime(new Date());
        employeeInfo.setDelFlag(CommonConstant.STATUS_DEL);
        return new R<>(employeeInfoService.updateById(employeeInfo));
    }


    /**
     * 编辑
     *
     * @param employeeInfo 实体
     * @return success/false
     */
    @PutMapping
    public R<Boolean> edit(@RequestBody EmployeeInfo employeeInfo) {
        if(employeeInfo.getDeptId()!=null){
            employeeInfo.setDeptName(deptService.selectById(employeeInfo.getDeptId()).getName());
        }
        employeeInfo.setUpdateTime(new Date());
        return new R<>(employeeInfoService.updateById(employeeInfo));
    }

    @RequestMapping("/upload")
    @ResponseBody
    public AjaxJson upload(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            try {
                /**
                 * 1、根据公司名称查询公司详情
                 * 2、判断当前登陆人有无权限导入该公司
                 */

                String username = getUserName();
                UserVO user = userService.findUserByUsername(username);
                if (user != null) {

                    List<EmployeeInfo> errorList = new ArrayList<>();
                    List<EmployeeInfo> duplicate = new ArrayList<>();
                    List<EmployeeInfo> insertList = new ArrayList<>();
                    ImportParams params = new ImportParams();
                    params.setTitleRows(0);
                    params.setHeadRows(1);
                    List<EmployeeInfo> list = ExcelImportUtil.importExcel(file.getInputStream(), EmployeeInfo.class, params);
                    String companys = user.getCommunityList().stream().map(CommunityInfoBean::getCommunityId).collect(Collectors.joining(","));

                    for (EmployeeInfo employeeInfo : list) {
                        Integer companyId = deptService.getCompanyByName(employeeInfo.getCompanyName());
                        if (companyId == null || companys.indexOf(companyId.toString()) < 0) {
                            errorList.add(employeeInfo);
                            continue;
                        }
                        //查重
                        if (employeeInfoService.checkDuplicate(employeeInfo.getPhone(), companyId)) {
                            duplicate.add(employeeInfo);
                            continue;
                        }
                        employeeInfo.setCompanyId(companyId);
                        //角色列表
                        if (StringUtils.isNotBlank(employeeInfo.getRoleName())) {
                            StringBuffer roleNames = new StringBuffer();
                            StringBuilder ids = new StringBuilder();
                            Arrays.asList(employeeInfo.getRoleName().split(",")).stream()
                                    .map(roleCode -> {
                                        SysRole role = sysRoleService.selectByCode(roleCode);
                                        roleNames.append(role.getRoleName());
                                        ids.append(role.getRoleId());
                                        roleNames.append(",");
                                        ids.append(",");
                                        return null;
                                    }).collect(Collectors.toList());
                            employeeInfo.setRoleName(roleNames.substring(0, roleNames.length() - 1));
                            employeeInfo.setRoleId(ids.substring(0, ids.length() - 1));
                            employeeInfo.setDeptId(deptService.getdeptByNameAndCompany(employeeInfo.getDeptName(), employeeInfo.getCompanyId()));
                        }
                        employeeInfo.setDelFlag(CommonConstant.STATUS_NORMAL);
                        insertList.add(employeeInfo);
                    }
                    if (!insertList.isEmpty()) {
                        employeeInfoService.insertBatch(insertList, insertList.size());
                    }
                    StringBuffer sb = new StringBuffer();
                    sb.append("成功导入：" + insertList.size() + "行");
                    if (duplicate.size() > 0) {
                        sb.append(",因手机号重复失败：" + duplicate.size() + "行");
                    }
                    if (errorList.size() > 0) {
                        sb.append(",因公司名称错误导入失败：" + errorList.size() + "行");
                    }

                    System.out.println(sb.toString());
                    j.setMsg(sb.toString());
                }

            } catch (ExcelImportException exception) {
                j.setSuccess(false);
                j.setMsg("Excel模板不合法或数据格式不正确，请检查");
            } catch (Exception e) {
                e.printStackTrace();
                j.setSuccess(false);
                j.setMsg("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

    public static void main(String[] args) {
        String i = "100";

        System.out.println(i.indexOf("100"));
    }
}
